package com.incar.chuxing.activity;

import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.webkit.CookieManager;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.incar.chuxing.R;
import com.incar.chuxing.activity.certification.CertifyCardActivity;
import com.incar.chuxing.activity.certification.CertifyDrivelicenseActivity;
import com.incar.chuxing.activity.driving.DrivingActivity;
import com.incar.chuxing.activity.personal.LoginActivity;
import com.incar.chuxing.api.ApiStore;
import com.incar.chuxing.api.RxApiStore;
import com.incar.chuxing.api.UrlContainer;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.base.BaseActivity;
import com.incar.chuxing.bean.CarDetailBean;
import com.incar.chuxing.bean.CarInfoBean;
import com.incar.chuxing.bean.CheckUserAccountBean;
import com.incar.chuxing.bean.CommonResultBean;
import com.incar.chuxing.bean.CountDownCloseEvent;
import com.incar.chuxing.bean.CountDownEvent;
import com.incar.chuxing.bean.DayRentPriceBean;
import com.incar.chuxing.bean.ExistingTravel;
import com.incar.chuxing.bean.GoldCarOneBean;
import com.incar.chuxing.bean.GoldCarTypeBean;
import com.incar.chuxing.bean.OcrOpenDoorBean;
import com.incar.chuxing.bean.QualificationBean;
import com.incar.chuxing.bean.RentDurationBean;
import com.incar.chuxing.bean.ZhiMaShouQuanBean;
import com.incar.chuxing.utils.AntiShake;
import com.incar.chuxing.utils.AppManager;
import com.incar.chuxing.utils.Dialogs.ConfirmAbatementDialog;
import com.incar.chuxing.utils.Dialogs.ConfirmDayRentDialog;
import com.incar.chuxing.utils.Dialogs.DialogOneButton;
import com.incar.chuxing.utils.Dialogs.DialogTwoButton;
import com.incar.chuxing.utils.Dialogs.NeedRechargeDialog;
import com.incar.chuxing.utils.ImageLoader;
import com.incar.chuxing.utils.IntentKey;
import com.incar.chuxing.utils.Logger;
import com.incar.chuxing.utils.NetUtils;
import com.incar.chuxing.utils.RxBus;
import com.incar.chuxing.utils.SPKey;
import com.incar.chuxing.utils.SPUtils;
import com.incar.chuxing.utils.SystemToastUtils;
import com.incar.chuxing.utils.ToastUtils;
import com.incar.chuxing.widget.CouponCountDown;
import com.incar.chuxing.widget.TabSwitchView;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class ScanResultActivity extends BaseActivity {

    @BindView(R.id.detail_name)
    TextView detailName;
    @BindView(R.id.price_rule)
    TextView priceRule;
    @BindView(R.id.detail_rl)
    RelativeLayout detailRl;
    @BindView(R.id.detail_iv)
    ImageView detailIv;
    @BindView(R.id.detail_license)
    TextView detailLicense;
    @BindView(R.id.detail_distance)
    TextView detailDistance;
    @BindView(R.id.detail_duration)
    TextView detailDuration;
    @BindView(R.id.detail_seats)
    TextView detailSeats;
    @BindView(R.id.detail_ll)
    LinearLayout detailLl;
    @BindView(R.id.detail_not_rent)
    LinearLayout detailNotRent;
    @BindView(R.id.detail_can_rent_ll)
    TextView detailCanRentLl;
    @BindView(R.id.checkbox)
    CheckBox abatementCheckBox;
    @BindView(R.id.car_detail_insure_tv)
    TextView carDetailInsureTv;
    @BindView(R.id.car_detail_rent)
    TextView carDetailRent;
    @BindView(R.id.detail_can_rent_rl)
    RelativeLayout detailCanRentRl;
    @BindView(R.id.detail_rank_iv)
    ImageView detailRankIv;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.detail_goldBean_tvLeft)
    TextView detailGoldBeanTvLeft;
    @BindView(R.id.detail_goldBean_tvRight)
    TextView detailGoldBeanTvRight;
    @BindView(R.id.detail_goldBean_ll)
    LinearLayout detailGoldBeanLl;
    @BindView(R.id.layout_scan_result)
    LinearLayout layoutScanResult;
    @BindView(R.id.tab_switch_view)
    TabSwitchView tabSwitchView;
    @BindView(R.id.coupon_countdown)
    CouponCountDown couponCountdown;
    private Context mContext = this;
    private String carId;
    private String description;
    private String goldHerf;
    private String isInsuranceCheck;
    private Disposable disposable;
    private CompositeDisposable compositeDisposable = new CompositeDisposable();


    @Override
    public int getLayoutId() {
        return R.layout.activity_scan_result;
    }

    @Override
    public void initView() {
        toolbar.setNavigationOnClickListener(v -> AppManager.getAppManager().finishActivity());
        Intent intent = getIntent();
        CarDetailBean.AttachmentBean.CarModelBean carModel = (CarDetailBean.AttachmentBean.CarModelBean) intent.getSerializableExtra("CarModel");
        RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL, 4).getCarInfo(((MyApplication) getApplication()).getRequestFieldMap(), carModel.getId())
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .onErrorResumeNext((Function<Throwable, ObservableSource<CarInfoBean>>) throwable ->
                        Observable.create(emitter -> {//接口错误返回一个空对象，以便后续兼容错误处理
                            emitter.onNext(new CarInfoBean());
                            emitter.onComplete();
                        })).subscribe(new Observer<CarInfoBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(CarInfoBean carInfoBean) {
                if (carInfoBean != null && carInfoBean.getStatus() == 200) {
                    carModel.setDayAbatement(carInfoBean.getAttachment().getDayAbatement());
                }
                getCarMoreInfo(carModel);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
        if (MainActivity.couponCountdown == null || MainActivity.couponCountdown.getStatus() == 2) {
            //主页面没有展示
            Logger.d("couponDown", "weixianshi");
            couponCountdown.setVisible(View.GONE);
        } else if (MainActivity.couponCountdown.getStatus() == 1) {
            couponCountdown.initTime(mContext, MainActivity.couponCountdown.getData());
            Logger.d("couponDown", "gengxin");
            //主页面未到时间
            disposable = RxBus.getInstance().toObservable(CountDownEvent.class).subscribe(countDownEvent -> {
                Logger.d("couponDown", countDownEvent.getCount() + "");
                if (countDownEvent.getCount() > 0) {
                    couponCountdown.update(countDownEvent.getCount());
                } else {
                    couponCountdown.stop();
                }
            });

        } else if (MainActivity.couponCountdown.getStatus() == 0) {
            //主页面已过期
            couponCountdown.initTime(mContext, MainActivity.couponCountdown.getData());
            Logger.d("couponDown", "guoqi");
            couponCountdown.stop();
        }
    }

    private void getCarMoreInfo(CarDetailBean.AttachmentBean.CarModelBean carModel) {
        if (carModel.getStatus().equals("10")) {
            detailNotRent.setVisibility(View.GONE);
            detailCanRentLl.setVisibility(View.VISIBLE);
            detailCanRentRl.setVisibility(View.VISIBLE);
            tabSwitchView.setVisibility(View.VISIBLE);
        } else {
            detailNotRent.setVisibility(View.VISIBLE);
            detailCanRentLl.setVisibility(View.GONE);
            detailCanRentRl.setVisibility(View.GONE);
            tabSwitchView.setVisibility(View.GONE);
        }
        description = carModel.getDescription().replace("+", "PLUS").toUpperCase();
        carId = carModel.getId();//车的id
        detailLicense.setText(carModel.getLicenseTag());//车牌
        detailName.setText(carModel.getBrand() + carModel.getModelCN());//品牌
        LatLng myPosition = new LatLng(Double.parseDouble(((MyApplication) getApplication()).getCurPosition()[0]), Double.parseDouble(((MyApplication) getApplication()).getCurPosition()[1]));
        LatLng carPosition = new LatLng(carModel.getLatitude(), carModel.getLongitude());
        detailDistance.setText(new DecimalFormat("0.0").format(DistanceUtil.getDistance(myPosition, carPosition) / 1000));//距离;
        detailDuration.setText(carModel.getMileage() + "");//续航
        detailSeats.setText(carModel.getSeat() + "");//座位数
        carDetailInsureTv.setText(new DecimalFormat("不计免赔(#.##元/单)").format(carModel.getAbatement()));
        //shareCheckBox.setChecked(true);//不急免赔默认true
        ImageLoader.getInstance().displayImage(getApplicationContext(), ((MyApplication) getApplication()).getImageUrl() + carModel.getPicture(), detailIv);//车的图片
        ImageLoader.getInstance().displayImage(getApplicationContext(), ((MyApplication) getApplication()).getImageUrl() + carModel.getIcon(), detailRankIv);
        if (TextUtils.isEmpty(SPUtils.getInstance(mContext).getStringValue(SPKey.ABATEMENT_CHECK)) ||
                SPUtils.getInstance(mContext).getStringValue(SPKey.ABATEMENT_CHECK).equals("0")) {
            abatementCheckBox.setChecked(false);
        } else {
            abatementCheckBox.setChecked(true);
        }


        tabSwitchView.setOnTabChangeListener(new TabSwitchView.OnTabChangeListener() {
            @Override
            public void onTabChange(int selectedIndex) {
                Logger.d("tabChange", selectedIndex + "");
                if (selectedIndex == 0) {//retType=0
                    carDetailRent.setText("开门用车");
                    carDetailInsureTv.setText(new DecimalFormat("不计免赔(#.##元/单)").format(carModel.getAbatement()));
                    ObjectAnimator animator = ObjectAnimator.ofFloat(priceRule, "rotationY", 0, 180, 360);
                    animator.setDuration(1000);
                    animator.start();
                } else if (selectedIndex == 1) {//retType=5
                    carDetailInsureTv.setText(new DecimalFormat("不计免赔(#.##元/小时)").format(900));
                    carDetailRent.setText("预订");
                    ObjectAnimator animator = ObjectAnimator.ofFloat(priceRule, "rotationY", 0, 180, 360);
                    animator.setDuration(1000);
                    animator.start();
                } else if (selectedIndex == 2) {//retType=2
                    carDetailInsureTv.setText(new DecimalFormat("不计免赔(#.##元/天)").format(carModel.getDayAbatement()));
                    carDetailRent.setText("预订");
                    ObjectAnimator animator = ObjectAnimator.ofFloat(priceRule, "rotationY", 0, 180, 360);
                    animator.setDuration(1000);
                    animator.start();
                }
            }

            @Override
            public void onHoursChosen(String selectedId) {

            }

            @Override
            public void onTimeChosen(String timeMills) {
                getRentDuration(timeMills);
            }
        });


        getGoldInfo();
    }


    private void getRentDuration(String timeMills) {
        showLoadingDialog();
        JSONObject bodyJson = new JSONObject();
        try {
            bodyJson.put("rentType", "3");
            bodyJson.put("rentEndTime", timeMills + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());
        RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL, 5).getRentDuration(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RentDurationBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(RentDurationBean result) {
                        dismissLoadingDialog();
                        if (result.getStatus() == 200) {
                            if (tabSwitchView != null) {
                                tabSwitchView.setDayRentDuration(timeMills, result.getAttachment().getPreRentTime());
                            }
                        } else {
                            ToastUtils.makeText(mContext, result.getMessage(), ToastUtils.LENGTH_SHORT).show();

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, getResources().getString(R.string.opterateBadNetwork), ToastUtils.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                        dismissLoadingDialog();
                    }
                });

    }

    private void getGoldInfo() {
        Observable<GoldCarTypeBean> goldTypeInfoObservable = RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL, 5).getGoldBeanTypeInfo(((MyApplication) MyApplication.getInstance()).getRequestFieldMap(), ((MyApplication) MyApplication.getInstance()).getAreaCode())
                //.retry(1)
                .onErrorResumeNext(throwable -> {
                    return Observable.create(emitter -> {
                        emitter.onNext(new GoldCarTypeBean());//没有围栏发送false
                        emitter.onComplete();
                    });
                })
                .share().cache()
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());

        //获取金豆车信息
        Observable<GoldCarOneBean> goldInfoObservable = RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL, 4).getGoldOneCar(((MyApplication) getApplication()).getRequestFieldMap(), carId)
                .retry(1)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());


        Observable.zip(goldTypeInfoObservable, goldInfoObservable, new BiFunction<GoldCarTypeBean, GoldCarOneBean, Boolean>() {
            @Override
            public Boolean apply(GoldCarTypeBean goldCarTypeBean, GoldCarOneBean goldCarOneBean) throws Exception {
                if (goldCarTypeBean != null && goldCarTypeBean.getMsg_code() == 200 && goldCarTypeBean.getAttachment() != null && goldCarTypeBean.getAttachment().getList() != null) {
                    HashMap<Integer, HashMap<String, String>> goldBeanInfoMap = new HashMap<>();

                    for (GoldCarTypeBean.AttachmentBean.ListBean listBean : goldCarTypeBean.getAttachment().getList()) {
                        HashMap<String, String> carTypeMap = new HashMap<>();
                        carTypeMap.put("half_gold_icon", listBean.getHalf_gold_icon());
                        carTypeMap.put("gold_icon", listBean.getGold_icon());
                        carTypeMap.put("icon_text", listBean.getIcon_text());
                        carTypeMap.put("show_full_text", listBean.getShow_full_text());
                        carTypeMap.put("show_half_text", listBean.getShow_half_text());
                        carTypeMap.put("link_text", listBean.getLink_text());
                        carTypeMap.put("link_href", listBean.getLink_href());
                        carTypeMap.put("real_time_icon", listBean.getReal_time_icon());
                        goldBeanInfoMap.put(listBean.getGold_car_type(), carTypeMap);
                    }

                    if (goldCarOneBean.getMsg_code() == 200 && goldCarOneBean.getAttachment() != null)
                        if (goldCarOneBean.getAttachment().getCar_status() == 0) {
                            detailGoldBeanLl.setVisibility(View.GONE);
                        } else {
                            detailGoldBeanLl.setVisibility(View.VISIBLE);
                            goldHerf = goldBeanInfoMap.get(goldCarOneBean.getAttachment().getGold_car_type()).get("link_href");
                            detailGoldBeanTvRight.setText(goldBeanInfoMap.get(goldCarOneBean.getAttachment().getGold_car_type()).get("link_text"));
                            if (goldCarOneBean.getAttachment().getCar_status() == 1) {//半金豆车
                                detailGoldBeanTvLeft.setText(goldBeanInfoMap.get(goldCarOneBean.getAttachment().getGold_car_type()).get("show_half_text").replace("[min]", goldCarOneBean.getAttachment().getShort_minutes() + ""));
                            } else if (goldCarOneBean.getAttachment().getCar_status() == 2) {//金豆车
                                detailGoldBeanTvLeft.setText(goldBeanInfoMap.get(goldCarOneBean.getAttachment().getGold_car_type()).get("show_full_text"));
                            }
                        }
                }
                return true;
            }
        }).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {
                compositeDisposable.add(d);
            }

            @Override
            public void onNext(Boolean a) {


            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    @OnClick({R.id.detail_goldBean_tvRight, R.id.price_rule, R.id.detail_can_rent_ll, R.id.car_detail_rent})
    public void onViewClicked(View view) {
        if (AntiShake.check(view.getId())) return;    //判断是否多次点击
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.price_rule:
                intent.setClass(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "计价规则");
                if (tabSwitchView.getSelected() == 0) {//共享
                    intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_price_shareRent_level) + "?model=" + description);
                } else {
                    intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_price_dayRent_level) + "?model=" + description);
                }
                mContext.startActivity(intent);
                break;
            case R.id.detail_can_rent_ll:
                //停车费补偿提示
                intent = new Intent(getApplicationContext(), WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_input_fee_guide));
                startActivity(intent);
                break;
            case R.id.car_detail_rent:
                canrentCar();
                break;
            case R.id.detail_goldBean_tvRight:
                //金豆车
                intent = new Intent(getApplicationContext(), WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, goldHerf);
                startActivity(intent);
                break;
        }
    }

    private void canrentCar() {
        if (!NetUtils.isNetworkAvailable(mContext)) {
            ToastUtils.makeText(mContext, "网络无法连接", 2000).show();
            return;
        }

        if (tabSwitchView.getSelected() == 1 && !tabSwitchView.isChosenTime()) {
            ToastUtils.makeText(mContext, "请选择用车时间", ToastUtils.LENGTH_SHORT).show();
            return;
        }

        if (tabSwitchView.getSelected() == 2 && !tabSwitchView.isChosenTime()) {
            ToastUtils.makeText(mContext, "请选择还车时间", ToastUtils.LENGTH_SHORT).show();
            return;
        }
        tipCheckAbatement();
    }


    private void tipCheckAbatement() {
        if (abatementCheckBox.isChecked()) {//勾选了不计免赔
            hasExistingTravelBeforeRent();
        } else {//未勾选
            ConfirmAbatementDialog confirmAbatementDialog = new ConfirmAbatementDialog(mContext);
            confirmAbatementDialog.setData(carDetailInsureTv.getText().toString().substring(4));
            confirmAbatementDialog.setOnCheckResultListener(new ConfirmAbatementDialog.OnCheckResultListener() {
                @Override
                public void onCheckDefault() {
                    SPUtils.getInstance(mContext).putStringValue(SPKey.ABATEMENT_CHECK, "1");
                    abatementCheckBox.setChecked(true);
                    confirmAbatementDialog.dismiss();
                    hasExistingTravelBeforeRent();

                }

                @Override
                public void onCheckNo() {
                    abatementCheckBox.setChecked(false);
                    confirmAbatementDialog.dismiss();
                    hasExistingTravelBeforeRent();
                }

                @Override
                public void onCheckOnce() {
                    abatementCheckBox.setChecked(true);
                    confirmAbatementDialog.dismiss();
                    hasExistingTravelBeforeRent();

                }

                @Override
                public void onCheckOk() {
                    abatementCheckBox.setChecked(true);
                    confirmAbatementDialog.dismiss();
                    hasExistingTravelBeforeRent();
                }
            });
            confirmAbatementDialog.show();
        }

    }

    /**
     * 检查是否有进行中的行程
     */
    private void hasExistingTravelBeforeRent() {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getExistingTravel(((MyApplication) getApplication()).getRequestFieldMap())
                .enqueue(new Callback<ExistingTravel>() {
                    @Override
                    public void onResponse(Call<ExistingTravel> call, final Response<ExistingTravel> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            dismissLoadingDialog();
                            if (200 == response.body().getStatus()) {
                                if (response.body().getAttachment().getIsUnfinished() != 0) {
                                    //有进行中的行程
                                    String orderId = response.body().getAttachment().getOrderId();
                                    int rentType = response.body().getAttachment().getRentType();
                                    int bookType = response.body().getAttachment().getOrderModel().getBookType();
                                    //送车上门订单，派单中或送车中（已送达不）
                                    if (response.body().getAttachment().getPreOrder() != null) {
                                        String preOrderId = response.body().getAttachment().getPreOrder().getId();
                                        int preOrderStatus = response.body().getAttachment().getPreOrder().getStatus();
                                        if (!TextUtils.isEmpty(response.body().getAttachment().getPreOrder().getId())
                                                && (preOrderStatus == 0 || preOrderStatus == 1)) {
                                            final DialogTwoButton unFinishTravelDialog = new DialogTwoButton(ScanResultActivity.this);
                                            unFinishTravelDialog.setMessage(getString(R.string.hasInDrivingOrder));
                                            unFinishTravelDialog.setYesOnclickListener("进入", () -> {
                                                Intent intent = new Intent(mContext, WebViewActivity.class);
                                                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_preOrder_bookingInfo)
                                                        + "?preOid=" + preOrderId);
                                                CookieManager cookieManager = CookieManager.getInstance();
                                                cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_preOrder_bookingInfo), "preOid=" + preOrderId);
                                                startActivity(intent);
                                                unFinishTravelDialog.dismiss();
                                            });
                                            unFinishTravelDialog.setNoOnclickListener("取消", () -> unFinishTravelDialog.dismiss());
                                            unFinishTravelDialog.setCancelable(false);
                                            unFinishTravelDialog.show();
                                            return;
                                        }
                                    }


                                    // 其他订单
                                    switch (response.body().getAttachment().getStatus()) {
                                        case 10: {
                                            final DialogTwoButton unFinishTravelDialog = new DialogTwoButton(ScanResultActivity.this);
                                            unFinishTravelDialog.setMessage("您有未完成的行程，是否继续");
                                            unFinishTravelDialog.setYesOnclickListener("进入", new DialogTwoButton.onYesOnclickListener() {
                                                @Override
                                                public void onYesClick() {
                                                    Intent intentInUse = new Intent(mContext, DrivingActivity.class);
                                                    intentInUse.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
                                                    startActivity(intentInUse);
                                                    AppManager.getAppManager().finishActivity();
                                                    unFinishTravelDialog.dismiss();
                                                }
                                            });
                                            unFinishTravelDialog.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                                                @Override
                                                public void onNoClick() {
                                                    unFinishTravelDialog.dismiss();
                                                }
                                            });
                                            unFinishTravelDialog.setCancelable(false);
                                            unFinishTravelDialog.show();
                                        }
                                        break;
                                        case 0: {
                                            final DialogTwoButton unFinishTravelDialog = new DialogTwoButton(ScanResultActivity.this);
                                            unFinishTravelDialog.setMessage("您有未完成的行程，是否继续");
                                            unFinishTravelDialog.setYesOnclickListener("进入", new DialogTwoButton.onYesOnclickListener() {
                                                @Override
                                                public void onYesClick() {
                                                    Intent intent = new Intent(mContext, MainActivity.class);
                                                    intent.putExtra("jumpCode", 4);
                                                    mContext.startActivity(intent);
                                                    AppManager.getAppManager().finishActivity();
                                                    unFinishTravelDialog.dismiss();
                                                }
                                            });
                                            unFinishTravelDialog.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                                                @Override
                                                public void onNoClick() {
                                                    unFinishTravelDialog.dismiss();
                                                }
                                            });
                                            unFinishTravelDialog.setCancelable(false);
                                            unFinishTravelDialog.show();
                                        }
                                        break;
                                        case 15: {
                                            final DialogTwoButton unFinishTravelDialog = new DialogTwoButton(ScanResultActivity.this);
                                            unFinishTravelDialog.setTitle("有未支付的订单");
                                            unFinishTravelDialog.setMessage("支付后才能订车");
                                            unFinishTravelDialog.setYesOnclickListener("支付", new DialogTwoButton.onYesOnclickListener() {
                                                @Override
                                                public void onYesClick() {
                                                    Intent intent = new Intent(mContext, WebViewActivity.class);
                                                    intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "订单支付");
                                                    CookieManager cookieManager = CookieManager.getInstance();
                                                    cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "orderId=" + orderId);
                                                    cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "oid=" + orderId);
                                                    cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "rentType=" + rentType);
                                                    cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "bookType=" + bookType);
                                                    intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment) + "?oid=" + orderId + "&rentType=" + rentType + "&bookType=" + bookType);
                                                    startActivity(intent);
                                                    AppManager.getAppManager().finishActivity();
                                                    unFinishTravelDialog.dismiss();
                                                }
                                            });
                                            unFinishTravelDialog.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                                                @Override
                                                public void onNoClick() {
                                                    unFinishTravelDialog.dismiss();
                                                }
                                            });
                                            unFinishTravelDialog.setCancelable(false);
                                            unFinishTravelDialog.show();
                                        }
                                        break;
                                    }

                                } else {//没有进行中订单
                                    isInsuranceCheck = abatementCheckBox.isChecked() ? "1" : "2";
                                    if (tabSwitchView.getSelected() == 0) {//共享
                                        rentCar(null);
                                    } else {//日租,小日租
                                        checkEnduranceMileage(carId);//检查续航
                                    }
                                }

                            } else if (20 == response.body().getStatus()) {
                                ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                                Intent intent = new Intent(mContext, LoginActivity.class);
                                startActivity(intent);
                            } else {
                                ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                                Logger.d("netError", "查询进行中订单失败");
                            }
                        } else

                        {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                            Logger.d("netError", "查询进行中订单失败");
                        }
                    }

                    @Override
                    public void onFailure(Call<ExistingTravel> call, Throwable t) {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                        Logger.d("netError", "查询进行中订单失败  " + t);
                    }
                });
    }

    private void checkAccount(ConfirmDayRentDialog confirmDayRentDialog) {
        showLoadingDialog();
        JSONObject bodyJson = new JSONObject();
        try {
            bodyJson.put("orderId", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());
        RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).checkUserMoney(body)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CheckUserAccountBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(CheckUserAccountBean result) {
                        dismissLoadingDialog();
                        if (result.getStatus() == 200) {
                            if (confirmDayRentDialog != null) {
                                confirmDayRentDialog.dismiss();
                            }
                            rentCar(confirmDayRentDialog);
                        } else if (result.getStatus() == 405) {
                            NeedRechargeDialog needRechargeDialog = new NeedRechargeDialog(mContext);
                            needRechargeDialog.setData(result.getAttachment());
                            needRechargeDialog.setNoOnclickListener(needRechargeDialog::dismiss);
                            needRechargeDialog.setYesOnclickListener(() -> {
                                Intent intent_wallet = new Intent(mContext, WebViewActivity.class);
                                intent_wallet.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "余额充值");
                                intent_wallet.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_recharge_order));
                                startActivity(intent_wallet);
                            });
                            needRechargeDialog.show();
                        } else {
                            ToastUtils.makeText(mContext, result.getMessage(), ToastUtils.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, getResources().getString(R.string.opterateBadNetwork), ToastUtils.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void checkEnduranceMileage(String carId) {
        showLoadingDialog();
        String rentType = "1";
        if (tabSwitchView.getSelected() == 1) {
            rentType = "5";
        } else if (tabSwitchView.getSelected() == 2) {
            rentType = "2";
        }
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).checkEnduranceMileage(((MyApplication) getApplication()).getRequestFieldMap(),
                carId, isInsuranceCheck,
                tabSwitchView.getSelected() == 1 || tabSwitchView.getSelected() == 2 ? "1" : null,
                rentType, tabSwitchView.getEndTime(), tabSwitchView.getLittleDaySelectedId()).enqueue(new Callback<CommonResultBean>() {
            @Override
            public void onResponse(Call<CommonResultBean> call, final Response<CommonResultBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                       getDayRentPrice(carId, isInsuranceCheck);
                    } else if (response.body().getStatus() == 600) {
                        dismissLoadingDialog();
                        DialogTwoButton dialogTwoButton = new DialogTwoButton(mContext);
                        dialogTwoButton.setMessage(response.body().getMessage());
                        dialogTwoButton.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                dialogTwoButton.dismiss();
                            }
                        });
                        dialogTwoButton.setYesOnclickListener("继续使用", new DialogTwoButton.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                dialogTwoButton.dismiss();
                                getDayRentPrice(carId, isInsuranceCheck);
                            }
                        });
                        dialogTwoButton.show();
                    } else if (response.body().getStatus() == 20) {
                        dismissLoadingDialog();
                        SystemToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        startActivity(intent);
                        AppManager.getAppManager().finishActivity();
                    } else {
                        dismissLoadingDialog();
                        SystemToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    dismissLoadingDialog();
                    SystemToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CommonResultBean> call, Throwable t) {
                dismissLoadingDialog();
                SystemToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    private void getDayRentPrice(String carId, String isAbatement) {
        showLoadingDialog();
        String rentType = "1";
        if (tabSwitchView.getSelected() == 1) {
            rentType = "5";
        } else if (tabSwitchView.getSelected() == 2) {
            rentType = "2";
        }
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getDayRentPrice(MyApplication.getInstance().getRequestFieldMap(),
                carId, isAbatement,
                tabSwitchView.getSelected() == 1 || tabSwitchView.getSelected() == 2 ? "1" : null, rentType, tabSwitchView.getEndTime(), tabSwitchView.getLittleDaySelectedId())
                .enqueue(new Callback<DayRentPriceBean>() {
                    @Override
                    public void onResponse(Call<DayRentPriceBean> call, final Response<DayRentPriceBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                dismissLoadingDialog();
                                ConfirmDayRentDialog confirmChooseDaysDialog = new ConfirmDayRentDialog(mContext);
                                confirmChooseDaysDialog.setChagableButtonText("开门用车");
                                confirmChooseDaysDialog.setData(response.body().getAttachment());
                                confirmChooseDaysDialog.setCarGrade(description);
                                confirmChooseDaysDialog.setNoOnclickListener(() -> {
                                    confirmChooseDaysDialog.dismiss();
                                });
                                confirmChooseDaysDialog.setYesOnclickListener(type -> {
                                    checkAccount(confirmChooseDaysDialog);
                                });
                                confirmChooseDaysDialog.show();
                            } else if (response.body().getStatus() == 20) {
                                dismissLoadingDialog();
                                SystemToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                                Intent intent = new Intent(mContext, LoginActivity.class);
                                startActivity(intent);
                                AppManager.getAppManager().finishActivity();
                            } else {
                                dismissLoadingDialog();
                                SystemToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<DayRentPriceBean> call, Throwable t) {
                        dismissLoadingDialog();
                        SystemToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }


    /**
     * 下单
     */
    public void rentCar(ConfirmDayRentDialog confirmDayRentDialog) {
        showLoadingDialog();
        String rentType = "1";
        if (tabSwitchView.getSelected() == 1) {
            rentType = "5";
        } else if (tabSwitchView.getSelected() == 2) {
            rentType = "2";
        }
        RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getOcrOpenDoor(((MyApplication) getApplication()).getRequestFieldMap(),
                carId, isInsuranceCheck, tabSwitchView.getEndTime() + "", tabSwitchView.getLittleDaySelectedId(),
                tabSwitchView.getSelected() == 1 ? "5" : tabSwitchView.getSelected() + "", rentType)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OcrOpenDoorBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(final OcrOpenDoorBean operateBean) {
                        dismissLoadingDialog();
                        Logger.i("ocr net openDoor", operateBean.getMessage() + "");
                        if (operateBean.getStatus() == 200) {
                            if (confirmDayRentDialog != null) {
                                confirmDayRentDialog.dismiss();
                            }
                            Intent intent = new Intent(mContext, DrivingActivity.class);
                            intent.putExtra(IntentKey.INTENT_ORDER_ID, operateBean.getAttachment().getOrder().getId());
                            intent.putExtra(IntentKey.INTENT_CAR_ID, carId);
                            intent.putExtra(IntentKey.INTENT_STEP, "ocrCar");
                            startActivity(intent);
                            if (couponCountdown != null)
                                couponCountdown.setVisible(View.GONE);
                            RxBus.getInstance().post(new CountDownCloseEvent(true));
                            AppManager.getAppManager().finishActivity();
                        } else if (operateBean.getStatus() == 20) {
                            if (confirmDayRentDialog != null) {
                                confirmDayRentDialog.dismiss();
                            }
                            ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                            Intent intent = new Intent(mContext, LoginActivity.class);
                            startActivity(intent);
                            AppManager.getAppManager().finishActivity();
                        } else if (operateBean.getStatus() == 401) {
                            if (confirmDayRentDialog != null) {
                                confirmDayRentDialog.dismiss();
                            }
                            checkUserCertifyStatus();
                        } else if (operateBean.getStatus() == 402 || operateBean.getStatus() == 403) {
                            if (confirmDayRentDialog != null) {
                                confirmDayRentDialog.dismiss();
                            }
                            checkUserCertifyStatus();
                        } else if (operateBean.getStatus() == 404) {
                            String orderId = operateBean.getAttachment().getOrder().getId();
                            int rentType = operateBean.getAttachment().getOrder().getRentType();
                            int bookType = operateBean.getAttachment().getOrder().getBookType();
                            String preOrderId = operateBean.getAttachment().getOrder().getPreOrderId();
                            int preOrderStatus = operateBean.getAttachment().getOrder().getPreOrderStatus();
                            //送车上门订单，派单中或送车中（已送达不）
                            if (!TextUtils.isEmpty(preOrderId) && (preOrderStatus == 0 || preOrderStatus == 1)) {
                                final DialogTwoButton unFinishTravelDialog = new DialogTwoButton(ScanResultActivity.this);
                                unFinishTravelDialog.setMessage(getString(R.string.hasInDrivingOrder));
                                unFinishTravelDialog.setYesOnclickListener("进入", () -> {
                                    Intent intent = new Intent(mContext, WebViewActivity.class);
                                    intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_preOrder_bookingInfo)
                                            + "?preOid=" + preOrderId);
                                    CookieManager cookieManager = CookieManager.getInstance();
                                    cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_preOrder_bookingInfo), "preOid=" + preOrderId);
                                    startActivity(intent);
                                    unFinishTravelDialog.dismiss();
                                });
                                unFinishTravelDialog.setNoOnclickListener("取消", () -> unFinishTravelDialog.dismiss());
                                unFinishTravelDialog.setCancelable(false);
                                unFinishTravelDialog.show();
                                return;
                            }
                            // 其他订单
                            switch (operateBean.getAttachment().getOrder().getStatus()) {
                                case 10: {
                                    final DialogTwoButton unFinishTravelDialog = new DialogTwoButton(ScanResultActivity.this);
                                    unFinishTravelDialog.setMessage(getString(R.string.hasInDrivingOrder));
                                    unFinishTravelDialog.setYesOnclickListener("进入", new DialogTwoButton.onYesOnclickListener() {
                                        @Override
                                        public void onYesClick() {
                                            if (confirmDayRentDialog != null) {
                                                confirmDayRentDialog.dismiss();
                                            }
                                            Intent intentInUse = new Intent(mContext, DrivingActivity.class);
                                            intentInUse.putExtra(IntentKey.INTENT_ORDER_ID, operateBean.getAttachment().getOrder().getId());
                                            intentInUse.putExtra(IntentKey.INTENT_CAR_ID, operateBean.getAttachment().getOrder().getCarId());
                                            startActivity(intentInUse);
                                            AppManager.getAppManager().finishActivity();
                                            unFinishTravelDialog.dismiss();
                                        }
                                    });
                                    unFinishTravelDialog.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                                        @Override
                                        public void onNoClick() {
                                            unFinishTravelDialog.dismiss();
                                        }
                                    });
                                    unFinishTravelDialog.setCancelable(false);
                                    unFinishTravelDialog.show();
                                }
                                break;
                                case 15: {
                                    final DialogTwoButton unFinishTravelDialog = new DialogTwoButton(ScanResultActivity.this);
                                    unFinishTravelDialog.setTitle("有未支付的订单");
                                    unFinishTravelDialog.setMessage("支付后才能订车");
                                    unFinishTravelDialog.setYesOnclickListener("支付", new DialogTwoButton.onYesOnclickListener() {
                                        @Override
                                        public void onYesClick() {
                                            if (confirmDayRentDialog != null) {
                                                confirmDayRentDialog.dismiss();
                                            }
                                            Intent intent = new Intent(mContext, WebViewActivity.class);
                                            intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "订单支付");
                                            CookieManager cookieManager = CookieManager.getInstance();
                                            cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "orderId=" + operateBean.getAttachment().getOrder().getId());
                                            cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "oid=" + operateBean.getAttachment().getOrder().getId());
                                            cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "rentType=" + operateBean.getAttachment().getOrder().getRentType());
                                            cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "bookType=" + operateBean.getAttachment().getOrder().getBookType());
                                            intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment) + "?oid=" + operateBean.getAttachment().getOrder().getId() + "&rentType=" + operateBean.getAttachment().getOrder().getRentType() + "&bookType=" + operateBean.getAttachment().getOrder().getBookType());
                                            startActivity(intent);
                                            AppManager.getAppManager().finishActivity();
                                            unFinishTravelDialog.dismiss();
                                        }
                                    });
                                    unFinishTravelDialog.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                                        @Override
                                        public void onNoClick() {
                                            unFinishTravelDialog.dismiss();
                                        }
                                    });
                                    unFinishTravelDialog.setCancelable(false);
                                    unFinishTravelDialog.show();
                                }
                                break;
                            }
                        } else if (operateBean.getStatus() == 405) {

                            final DialogTwoButton inCarDialog = new DialogTwoButton(ScanResultActivity.this);
                            inCarDialog.setTitle("提示");
                            inCarDialog.setMessage(operateBean.getMessage());
                            inCarDialog.setYesOnclickListener("去往我的钱包", new DialogTwoButton.onYesOnclickListener() {
                                @Override
                                public void onYesClick() {
                                    if (confirmDayRentDialog != null) {
                                        confirmDayRentDialog.dismiss();
                                    }
                                    Intent intent_wallet = new Intent(mContext, WebViewActivity.class);
                                    intent_wallet.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "我的钱包");
                                    CookieManager cookieManager2 = CookieManager.getInstance();
                                    cookieManager2.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_my_wallet), "isExist=" + SPUtils.getInstance(mContext).getIntValue(SPKey.DOT_ISEXITE));
                                    cookieManager2.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_my_wallet), "RushedSendPicture=" + SPUtils.getInstance(mContext).getStringValue(SPKey.WALLET_PICTURE));
                                    intent_wallet.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_my_wallet));
                                    startActivity(intent_wallet);
                                    inCarDialog.dismiss();
                                }
                            });
                            inCarDialog.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                                @Override
                                public void onNoClick() {
                                    inCarDialog.dismiss();
                                }
                            });
                            inCarDialog.setCancelable(false);
                            inCarDialog.show();
                        } else if (operateBean.getStatus() == 409) {
                            final DialogTwoButton inCarDialog = new DialogTwoButton(mContext);
                            inCarDialog.setTitle("提示");
                            inCarDialog.setMessage(operateBean.getMessage());
                            inCarDialog.setYesOnclickListener("去认证", new DialogTwoButton.onYesOnclickListener() {
                                @Override
                                public void onYesClick() {
                                    if (confirmDayRentDialog != null) {
                                        confirmDayRentDialog.dismiss();
                                    }
                                    Intent intent = new Intent(mContext, WebViewActivity.class);
                                    intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_margin_certification));
                                    startActivity(intent);
                                    AppManager.getAppManager().finishActivity();
                                    inCarDialog.dismiss();
                                }
                            });
                            inCarDialog.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                                @Override
                                public void onNoClick() {
                                    inCarDialog.dismiss();
                                }
                            });
                            inCarDialog.show();

                        } else if (operateBean.getStatus() == 410) {
                            final DialogTwoButton inCarDialog = new DialogTwoButton(mContext);
                            inCarDialog.setTitle("提示");
                            inCarDialog.setMessage(operateBean.getMessage());
                            inCarDialog.setYesOnclickListener("去认证", new DialogTwoButton.onYesOnclickListener() {
                                @Override
                                public void onYesClick() {
                                    if (confirmDayRentDialog != null) {
                                        confirmDayRentDialog.dismiss();
                                    }
                                    getZhiMaShouQuanUrl();
                                    inCarDialog.dismiss();
                                }
                            });
                            inCarDialog.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                                @Override
                                public void onNoClick() {
                                    inCarDialog.dismiss();
                                }
                            });
                            inCarDialog.show();
                        } else if (operateBean.getStatus() == 413) {
                            final DialogTwoButton inCarDialog = new DialogTwoButton(ScanResultActivity.this);
                            inCarDialog.setTitle("您有未处理的违章");
                            inCarDialog.setMessage("请您处理后再用车");
                            inCarDialog.setYesOnclickListener("查看详情", new DialogTwoButton.onYesOnclickListener() {
                                @Override
                                public void onYesClick() {
                                    if (confirmDayRentDialog != null) {
                                        confirmDayRentDialog.dismiss();
                                    }
                                    Intent intent_weizhang = new Intent(mContext, WebViewActivity.class);
                                    intent_weizhang.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "违章查询");
                                    intent_weizhang.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_break_rules));
                                    startActivity(intent_weizhang);
                                    inCarDialog.dismiss();
                                }
                            });
                            inCarDialog.setNoOnclickListener("好的", new DialogTwoButton.onNoOnclickListener() {
                                @Override
                                public void onNoClick() {
                                    inCarDialog.dismiss();
                                }
                            });
                            inCarDialog.setCancelable(false);
                            inCarDialog.show();
                        } else if (operateBean.getStatus() == 414) {
                            final DialogTwoButton inCarDialog = new DialogTwoButton(mContext);
                            inCarDialog.setTitle("信用等级不足");
                            inCarDialog.setMessage("是否升级信用等级？");
                            inCarDialog.setYesOnclickListener("了解一下", () -> {
                                if (confirmDayRentDialog != null) {
                                    confirmDayRentDialog.dismiss();
                                }
                                Intent intent = new Intent();
                                intent.setClass(mContext, WebViewActivity.class);
                                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_success_identity));
                                startActivity(intent);
                                inCarDialog.dismiss();
                            });
                            inCarDialog.setNoOnclickListener("取消", () -> inCarDialog.dismiss());
                            inCarDialog.show();
                        } else if (operateBean.getStatus() == 418) {
                            startActivity(new Intent(mContext, CertifyDrivelicenseActivity.class));
                        } else {
                            final DialogOneButton inCarDialog = new DialogOneButton(mContext);
                            inCarDialog.setTitle("订车失败");
                            inCarDialog.setMessage(operateBean.getMessage());
                            inCarDialog.setYesOnclickListener("知道了", new DialogOneButton.onYesOnclickListener() {
                                @Override
                                public void onYesClick() {
                                    if (confirmDayRentDialog != null) {
                                        confirmDayRentDialog.dismiss();
                                    }
                                    inCarDialog.dismiss();
                                }
                            });
                            inCarDialog.show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.i("ocr net openDoor", "onFailure" + e.getMessage());
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    //验证用户汽车认证状态
    private void checkUserCertifyStatus() {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getUserStatus(((MyApplication) getApplication()).getRequestFieldMap()).enqueue(new Callback<QualificationBean>() {
            @Override
            public void onResponse(Call<QualificationBean> call, Response<QualificationBean> response) {
                dismissLoadingDialog();
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        SPUtils.getInstance(mContext).putStringValue(SPKey.REAL_NAME_STATUS, response.body().getAttachment().getIdentityStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.LICENSE_CAR_STATUS, response.body().getAttachment().getLicenseStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.DEPOSIT_CAR_STATUS, response.body().getAttachment().getDepositStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.DEPOSIT_AMOUNT, response.body().getAttachment().getCarBail() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.JISHEN_STATUS, response.body().getAttachment().getStatus() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.ZHIMA_STATUS, response.body().getAttachment().getAuthorize() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.ZHIMA_FEN, response.body().getAttachment().getScore() + "");
                        SPUtils.getInstance(mContext).putStringValue(SPKey.XINYONG_LEVEL, response.body().getAttachment().getLevel() + "");


                        int deposit = response.body().getAttachment().getDepositStatus();
                        int authorize = response.body().getAttachment().getAuthorize();
                        String licenseStatus = response.body().getAttachment().getLicenseStatus() + "";
                        if (authorize != 1 && deposit == 0) {
                            Intent intent = new Intent(mContext, WebViewActivity.class);
                            intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_credit_auth));
                            startActivity(intent);
                            AppManager.getAppManager().finishActivity();
                        } else if ("11".equals(licenseStatus)) {
                            final DialogOneButton dialogOneButton = new DialogOneButton(mContext);
                            dialogOneButton.setTitle("提示");
                            dialogOneButton.setMessage("身份信息审核中，请耐心等待");
                            dialogOneButton.setCancelable(false);
                            dialogOneButton.setCanceledOnTouchOutside(false);
                            dialogOneButton.setYesOnclickListener("确定", new DialogOneButton.onYesOnclickListener() {
                                @Override
                                public void onYesClick() {
                                    dialogOneButton.dismiss();
                                }
                            });
                            dialogOneButton.show();
                        } else {
                            //未实名
                            Intent intent = new Intent(mContext, CertifyCardActivity.class);
                            startActivity(intent);
                            AppManager.getAppManager().finishActivity();
                        }
                    } else if (response.body().getStatus() == 20) {
                        ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        startActivity(intent);
                        AppManager.getAppManager().finishAllActivity();
                    } else {
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<QualificationBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    protected void onDestroy() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }

    public void getZhiMaShouQuanUrl() {
        showLoadingDialog();
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getZhiMaAuthorizeUrl(((MyApplication) getApplication()).getRequestFieldMap()).enqueue(new Callback<ZhiMaShouQuanBean>() {
            @Override
            public void onResponse(Call<ZhiMaShouQuanBean> call, Response<ZhiMaShouQuanBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        dismissLoadingDialog();
                        String url = response.body().getAttachment().getUrl();
                        doVerify(url);
                    } else {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    dismissLoadingDialog();
                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ZhiMaShouQuanBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 启动支付宝进行认证
     *
     * @param url 开放平台返回的URL
     */
    private void doVerify(String url) {
        if (hasApplication()) {
            SPUtils.getInstance(mContext).putStringValue(SPKey.INTENT_ZHIMA, "ScanResultActivity");
            Intent action = new Intent(Intent.ACTION_VIEW);
            StringBuilder builder = new StringBuilder();
            // 这里使用固定appid 20000067
            builder.append("alipays://platformapi/startapp?appId=20000067&url=");
            builder.append(URLEncoder.encode(url));
            action.setData(Uri.parse(builder.toString()));
            startActivity(action);
            AppManager.getAppManager().finishActivity();
        } else {
            // 处理没有安装支付宝的情况
            new AlertDialog.Builder(this)
                    .setMessage("是否下载并安装支付宝完成认证?")
                    .setPositiveButton("好的", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent action = new Intent(Intent.ACTION_VIEW);
                            action.setData(Uri.parse("https://m.alipay.com"));
                            startActivity(action);
                        }
                    }).setNegativeButton("算了", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).show();
        }
    }

    /**
     * 判断是否安装了支付宝
     *
     * @return true 为已经安装
     */
    private boolean hasApplication() {
        PackageManager manager = getPackageManager();
        Intent action = new Intent(Intent.ACTION_VIEW);
        action.setData(Uri.parse("alipays://"));
        List list = manager.queryIntentActivities(action, PackageManager.GET_RESOLVED_FILTER);
        return list != null && list.size() > 0;
    }

}
